import React from 'react'
import {View, Text,StyleSheet,FlatList} from 'react-native'
import ChatToolBar from '../../component/ChatToolBar/ChatToolBar'
import MsgCell from '../../component/MsgCell'
import * as types from '../../const/actionTypes'
import MsgCenter from "../../util/socket/MsgCenter";

export default class Chat extends React.Component {



    componentWillMount(){
        console.log('准备挂载!')
        //设置
        const {navigation} = this.props;
        const chatUserId = navigation.getParam('chatUserId');
        this.setState({
            chatUserId:chatUserId
        })
    }

    constructor(props) {
        super(props)
        this.state={
            chatUserId:null
        }
    }



    _msgArray = ()=>{
        let msgMap = JSON.parse(this.props.msgMap)
        let msgRecord = msgMap[this.state.chatUserId]
        if(msgRecord){
            return msgRecord.msgArray
        }else {
            return []
        }
    }


    render() {

        return (
        <View style={styles.container}>
            <FlatList renderItem={this._renderItem} data={this._msgArray()} keyExtractor={(item)=>item.guid}  />
            <ChatToolBar toCamera={this._toCamera}  sendTextMsg={this._sendTextMsg}   />
        </View>
    )
    }

    _toCamera = ()=>{
        const { navigate } = this.props.navigation;
        navigate('Camera')
    }

    _sendTextMsg = (content)=>{
        console.log('正在发送文字:'+content)
        const type = MsgCenter.MsgType.TEXT
        const chatType = MsgCenter.ChatType.SINGLE
        //TODO saga处理发送
        this.props.dispatch({type:types.SEND_MSG,payload:{type, chatType , content}})
    }

    _renderItem = ({item})=>(
        <MsgCell userId={this.props.userId} item={item} />
    )

}

const styles = StyleSheet.create({
   container:{
       flex: 1
   }
})